<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useLoading } from '@sa/hooks';
import { fetchCreateWithdrawConfig, fetchUpdateWithdrawConfig } from '@/service/api/business/withdraw-fee';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'WithdrawOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Business.WithdrawFee | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const { loading: submitLoading, startLoading: startSubmitLoading, endLoading: endSubmitLoading } = useLoading();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增提现费率',
    edit: '编辑提现费率'
  };
  return titles[props.operateType];
});

type Model = Api.Business.WithdrawFeeOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    fee: '',
    status: 0,
    username: '',
    password: ''
  };
}

type RuleKey = Extract<keyof Model, 'fee' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule | App.Global.FormRule[]> = {
  fee: createRequiredRule('提现费率不能为空'),
  status: createRequiredRule('启用状态不能为空')
};

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
    // 编辑时不需要用户名和密码
    model.username = '';
    model.password = '';
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  startSubmitLoading();

  try {
    if (props.operateType === 'add') {
      const { fee, status, username, password } = model;
      const { error } = await fetchCreateWithdrawConfig({
        fee,
        status,
        username,
        password
      });
      if (error) return;
    }

    if (props.operateType === 'edit') {
      const { id, fee, status } = model;
      const { error } = await fetchUpdateWithdrawConfig({
        id,
        fee,
        status
      });
      if (error) return;
    }

    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    endSubmitLoading();
  }
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="500" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NDivider>费率设置</NDivider>

        <NFormItem label="提现费率" path="fee">
          <NInputNumber
            v-model:value="model.fee"
            placeholder="请输入提现费率(如0.03表示百分之三)"
            :min="0"
            :max="100"
            :precision="2"
            :step="0.01"
            class="w-full"
          ></NInputNumber>
        </NFormItem>

        <NFormItem label="启用状态" path="status">
          <DictRadio v-model:value="model.status" dict-code="sys_normal_disable" />
        </NFormItem>

      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
